use super::lexer::{Error, Lexer, Token};
use crate::T;

pub trait Parse<'lex> {
	type Output;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>>;
}

/// TypeScript declaration file
#[derive(Debug, Clone)]
pub struct DeclFile<'src> {
	pub declarations: Vec<Declaration<'src>>,
}
impl<'src, 'lex> Parse<'lex> for DeclFile<'src> {
	type Output = DeclFile<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		let mut declarations = Vec::new();
		while r.peek().is_ok() {
			declarations.push(Declaration::parse(r)?);
		}
		Ok(DeclFile { declarations })
	}
}

/// TypeScript declaration
#[derive(Debug, Clone)]
pub enum Declaration<'src> {
	TypeAlias(TypeAlias<'src>),
	Const(Const<'src>),
	Enum(Enum<'src>),
	Interface(Interface<'src>),
	Function(Function<'src>),
	Class(Class<'src>),
	Namespace(Namespace<'src>),
	Import(Import<'src>),
	Export(Export<'src>),
}
impl<'src, 'lex> Parse<'lex> for Declaration<'src> {
	type Output = Declaration<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		let _has_export = r.if_is_ident_next("export");
		let _has_declare = r.if_is_ident_next("declare");
		let _has_default = r.if_is_ident_next("default");
		let _has_abstract = r.if_is_ident_next("abstract");

		// Determine declaration type
		let decl = match r.peek()?.token {
			Token::Ident("import") => {
				r.next()?;
				if _has_export {
					Declaration::TypeAlias(TypeAlias::parse(r)?)
				} else {
					Declaration::Import(Import::parse(r)?)
				}
			}
			Token::Ident("namespace") => {
				r.next()?;
				Declaration::Namespace(Namespace::parse(r)?)
			}
			Token::Ident("type") => {
				r.next()?;
				match r.peek()?.token {
					T!("*") | T!("{") if _has_export => {
						Declaration::Export(Export::parse(r)?) //
					}
					_ => Declaration::TypeAlias(TypeAlias::parse(r)?),
				}
			}
			Token::Ident("const") | Token::Ident("let") => {
				r.next()?;
				if r.if_is_ident_next("enum") {
					Declaration::Enum(Enum::parse(r)?)
				} else {
					Declaration::Const(Const::parse(r)?)
				}
			}
			Token::Ident("enum") => {
				r.next()?;
				Declaration::Enum(Enum::parse(r)?)
			}
			Token::Ident("interface") => {
				r.next()?;
				Declaration::Interface(Interface::parse(r)?)
			}
			Token::Ident("function") => {
				r.next()?;
				Declaration::Function(Function::parse(r)?)
			}
			Token::Ident("class") => {
				r.next()?;
				Declaration::Class(Class::parse(r)?)
			}
			Token::Ident(_) | T!("*") | T!("{") if _has_export => {
				Declaration::Export(Export::parse(r)?) //
			}
			v => {
				return Err(Error::Unsupport(r.span(), v, "declaration item")); //
			}
		};

		Ok(decl)
	}
}

/// Import declaration
#[derive(Debug, Clone)]
pub struct Import<'src> {
	pub specifiers: Vec<Specifier<'src>>,
	pub module: &'src str,
}
impl<'src, 'lex> Parse<'lex> for Import<'src> {
	type Output = Import<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// r.expect_ident_eq("import")?;
		let mut module = "";
		let specifiers = Specifier::parse_list(r)?;
		if r.if_is_ident_next("from") {
			module = r.expect_string()?;
		}
		r.expect(T!(";"))?;
		Ok(Import { specifiers, module })
	}
}

/// Export declaration
#[derive(Debug, Clone)]
pub struct Export<'src> {
	pub specifiers: Vec<Specifier<'src>>,
	pub module: &'src str,
}
impl<'src, 'lex> Parse<'lex> for Export<'src> {
	type Output = Export<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		let mut module = "";
		let specifiers = Specifier::parse_list(r)?;
		if r.if_is_ident_next("from") {
			module = r.expect_string()?;
		}
		r.expect(T!(";"))?;
		Ok(Export { specifiers, module })
	}
}

/// Import specifier
#[derive(Debug, Clone)]
pub enum Specifier<'src> {
	Named(Vec<(&'src str, Option<&'src str>)>),
	Default(&'src str),
	Namespace(&'src str),
}
impl<'src, 'lex> Parse<'lex> for Specifier<'src> {
	type Output = Specifier<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		let _is_type_import = r.if_is_ident_next("type");
		match r.peek()?.token {
			T!("*") => {
				// * as ident
				r.next()?;
				if r.if_is_ident_next("as") {
					let name = r.expect_ident()?;
					Ok(Specifier::Namespace(name))
				} else {
					Ok(Specifier::Namespace(""))
					// Err(Error::Unsupport(r.span(), T!("*"), "* as ___"))
				}
			}
			T!("{") => {
				// { type ident as ident,ident,ident as ident }
				r.next()?;
				let mut list = vec![];
				while !r.is(T!("}")) {
					let _is_type_import = r.if_is_ident_next("type");
					let name = r.expect_ident()?;
					let alias = if r.if_is_next(Token::Ident("as")) {
						Some(r.expect_ident()?)
					} else {
						None
					};
					list.push((name, alias));
					r.if_is_next(T!(","));
				}
				r.expect(T!("}"))?;
				Ok(Specifier::Named(list))
			}
			Token::Ident(name) => {
				r.next()?;
				Ok(Specifier::Default(name))
			}
			v => Err(Error::Unsupport(r.span(), v, "import item")),
		}
	}
}
impl<'src> Specifier<'src> {
	pub fn parse_list<'lex>(r: &mut Lexer<'lex>) -> Result<Vec<Specifier<'lex>>, Error<'lex>> {
		let mut specifiers = Vec::new();
		loop {
			specifiers.push(Specifier::parse(r)?);
			if !r.if_is_next(T!(",")) {
				break;
			}
		}
		Ok(specifiers)
	}
}

/// Namespace declaration
/// namespace ident {
/// 	Declaration ...
/// }
#[derive(Debug, Clone)]
pub struct Namespace<'src> {
	pub name: &'src str,
	pub declarations: Vec<Declaration<'src>>,
}
impl<'src, 'lex> Parse<'lex> for Namespace<'src> {
	type Output = Namespace<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// r.expect_ident_eq("namespace")?;
		let name = r.expect_ident()?;
		r.expect(T!("{"))?;
		let mut declarations = Vec::new();
		while !r.is(T!("}")) {
			declarations.push(Declaration::parse(r)?);
		}
		r.expect(T!("}"))?;
		Ok(Namespace { name, declarations })
	}
}

/// Type alias declaration
/// type ident<type_param...> = type_expr;
#[derive(Debug, Clone)]
pub struct TypeAlias<'src> {
	pub name: &'src str,
	pub type_params: Vec<TypeParam<'src>>,
	pub type_expr: TypeExpr<'src>,
}
impl<'src, 'lex> Parse<'lex> for TypeAlias<'src> {
	type Output = TypeAlias<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// r.expect_ident_eq("type")?;
		let name = r.expect_ident()?;
		let type_params = TypeParam::parse_list(r)?;
		r.expect(T!("="))?;
		let type_expr = TypeExpr::parse(r)?;
		r.expect(T!(";"))?;

		Ok(TypeAlias {
			name,
			type_params,
			type_expr,
		})
	}
}

/// Constant declaration
/// const ident:type_expr = expr;
#[derive(Debug, Clone)]
pub struct Const<'src> {
	pub name: &'src str,
	pub type_expr: TypeExpr<'src>,
	pub value: Option<Expr<'src>>,
}
impl<'src, 'lex> Parse<'lex> for Const<'src> {
	type Output = Const<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// r.expect_ident_eq("const")?;
		let name = r.expect_ident()?;
		// Check for type annotation
		let type_expr = if r.if_is_next(T!(":")) {
			TypeExpr::parse(r)?
		} else {
			TypeExpr::Unsupport
		};
		// Check for value assignment
		let value = if r.if_is_next(T!("=")) {
			Some(Expr::parse(r)?) //
		} else {
			None
		};
		r.expect(T!(";"))?;
		Ok(Const { name, type_expr, value })
	}
}

/// Function declaration
/// function ident<type_param...>(parameter...): type_expr;
#[derive(Debug, Clone)]
pub struct Function<'src> {
	pub name: &'src str,
	pub type_params: Vec<TypeParam<'src>>,
	pub parameters: Vec<FuncParam<'src>>,
	pub return_type: TypeExpr<'src>,
}
impl<'src, 'lex> Parse<'lex> for Function<'src> {
	type Output = Function<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// r.expect_ident_eq("function")?;
		let name = r.expect_ident()?;
		let type_params = TypeParam::parse_list(r)?;
		let parameters = FuncParam::parse_list(r)?;
		r.expect(T!(":"))?;
		let return_type = TypeExpr::parse(r)?;
		r.expect(T!(";"))?;
		Ok(Function {
			name,
			type_params,
			parameters,
			return_type,
		})
	}
}

/// Enum declaration
/// enum ident {
///		enum_member, *
/// }
#[derive(Debug, Clone)]
pub struct Enum<'src> {
	pub name: &'src str,
	pub is_const: bool,
	pub members: Vec<EnumMember<'src>>,
}
impl<'src, 'lex> Parse<'lex> for Enum<'src> {
	type Output = Enum<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// r.expect_ident_eq("enum")?;
		let name = r.expect_ident()?;
		r.expect(T!("{"))?;
		let mut members = Vec::new();
		while !r.is(T!("}")) {
			members.push(EnumMember::parse(r)?);
			r.if_is_next(T!(","));
		}
		r.expect(T!("}"))?;
		Ok(Enum {
			name,
			is_const: true, // d.ts enums are usually const
			members,
		})
	}
}

/// Enum member
/// ident = expr
#[derive(Debug, Clone)]
pub struct EnumMember<'src> {
	pub name: &'src str,
	pub value: Option<Expr<'src>>,
}
impl<'src, 'lex> Parse<'lex> for EnumMember<'src> {
	type Output = EnumMember<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		let name = r.expect_ident()?;
		let value = if r.if_is_next(T!("=")) {
			Some(Expr::parse(r)?) //
		} else {
			None
		};
		Ok(EnumMember { name, value })
	}
}

/// Interface declaration
/// interface ident<type_param...> extends type_expr... {
/// 	interface_member...
/// }
#[derive(Debug, Clone)]
pub struct Interface<'src> {
	pub name: &'src str,
	pub type_params: Vec<TypeParam<'src>>,
	pub extends: Vec<TypeExpr<'src>>,
	pub members: Vec<InterfaceMember<'src>>,
}
impl<'src, 'lex> Parse<'lex> for Interface<'src> {
	type Output = Interface<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// r.expect_ident_eq("interface")?;
		let name = r.expect_ident()?;
		let type_params = TypeParam::parse_list(r)?;

		let extends = if r.if_is_ident_next("extends") {
			TypeExpr::parse_list(r)?
		} else {
			Vec::new()
		};

		r.expect(T!("{"))?;
		let mut members = Vec::new();
		while !r.is(T!("}")) {
			// TODO
			members.push(InterfaceMember::parse(r)?);
			// r.next_until(T!("}"))?;
		}
		r.expect(T!("}"))?;
		r.if_is_next(T!(";"));

		Ok(Interface {
			name,
			type_params,
			extends,
			members,
		})
	}
}

/// Interface member
#[derive(Debug, Clone)]
pub enum InterfaceMember<'src> {
	Property(Property<'src>),
	Method(Method<'src>),
	IndexSignature(IndexSignature<'src>),
	CallSignature(CallSignature<'src>),
	ConstructSignature(ConstructSignature<'src>),
}
impl<'src, 'lex> Parse<'lex> for InterfaceMember<'src> {
	type Output = InterfaceMember<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// 检查是否是 readonly 属性
		let is_readonly = r.if_is_ident_next("readonly");

		// 检查是否是索引签名 [key: string]: type
		if r.is(T!("[")) {
			return parse_index_signature(r, is_readonly);
		}

		// 检查是否是构造签名 new (...)
		if r.if_is_ident_next("new") {
			return parse_construct_signature(r);
		}

		// 检查是否是调用签名 (...): type
		if r.is(T!("(")) || r.is(T!("<")) {
			return parse_call_signature(r);
		}

		// 解析成员名称
		let name = r.expect_ident()?;

		// 检查是否是可选成员
		let is_optional = r.if_is_next(T!("?"));

		// 根据接下来的符号判断是属性还是方法
		r.push();
		match r.peek()?.token {
			// 属性: name: type;
			T!(":") => {
				r.next()?; // 消费冒号
				let type_expr = TypeExpr::parse(r)?;
				r.expect(T!(";"))?;
				r.pop(false);
				Ok(InterfaceMember::Property(Property {
					name,
					is_optional,
					is_readonly,
					type_expr,
				}))
			}
			// 方法: name<?>(...): type;
			T!("<") | T!("(") => {
				// 解析泛型参数
				let type_params = TypeParam::parse_list(r)?;
				// 解析参数列表
				let parameters = FuncParam::parse_list(r)?;
				// 解析返回类型
				let return_type = if r.if_is_next(T!(":")) {
					TypeExpr::parse(r)?
				} else {
					TypeExpr::Unsupport
				};
				r.expect(T!(";"))?;
				r.pop(false);
				Ok(InterfaceMember::Method(Method {
					name,
					is_optional,
					type_params,
					parameters,
					return_type,
				}))
			}
			_ => {
				// 回退到属性解析
				r.pop(true);
				// r.seek(start_pos);
				// let name = r.expect_ident()?;
				// let is_optional = r.if_is_next(T!("?"));
				r.expect(T!(":"))?;
				let type_expr = TypeExpr::parse(r)?;
				r.expect(T!(";"))?;

				Ok(InterfaceMember::Property(Property {
					name,
					is_optional,
					is_readonly: false,
					type_expr,
				}))
			}
		}
	}
}

// 解析索引签名: [key: string]: type
// [ParticleType.POINT]: PointParticleParameters;
fn parse_index_signature<'lex>(r: &mut Lexer<'lex>, is_readonly: bool) -> Result<InterfaceMember<'lex>, Error<'lex>> {
	r.expect(T!("["))?;
	r.push();
	fn parse_with_name<'lex>(r: &mut Lexer<'lex>, is_readonly: bool) -> Result<InterfaceMember<'lex>, Error<'lex>> {
		// 解析索引参数
		let param_name = r.expect_ident()?;
		r.expect(T!(":"))?;

		// 索引键类型通常是 string | number | symbol
		let key_type = TypeExpr::parse(r)?;
		r.expect(T!("]"))?;

		// 解析返回类型
		r.expect(T!(":"))?;
		let return_type = TypeExpr::parse(r)?;
		r.expect(T!(";"))?;

		Ok(InterfaceMember::IndexSignature(IndexSignature {
			parameter: FuncParam {
				name: param_name,
				type_expr: key_type,
				is_optional: false,
				dotdotdot: false,
			},
			is_readonly,
			return_type,
		}))
	}
	match parse_with_name(r, is_readonly) {
		Ok(v) => {
			r.pop(false);
			Ok(v)
		}
		Err(_) => {
			r.pop(true);
			// 索引键类型通常是 string | number | symbol
			let key_type = TypeExpr::parse(r)?;
			r.expect(T!("]"))?;

			// 解析返回类型
			r.expect(T!(":"))?;
			let return_type = TypeExpr::parse(r)?;
			r.expect(T!(";"))?;

			Ok(InterfaceMember::IndexSignature(IndexSignature {
				parameter: FuncParam {
					name: "",
					type_expr: key_type,
					is_optional: false,
					dotdotdot: false,
				},
				is_readonly,
				return_type,
			}))
		}
	}
}

// 解析调用签名: (...): type
fn parse_call_signature<'lex>(r: &mut Lexer<'lex>) -> Result<InterfaceMember<'lex>, Error<'lex>> {
	// 解析泛型参数
	let type_params = TypeParam::parse_list(r)?;
	// 解析参数列表
	let parameters = FuncParam::parse_list(r)?;
	// 解析返回类型
	let return_type = if r.if_is_next(T!(":")) {
		TypeExpr::parse(r)?
	} else {
		TypeExpr::Unsupport
	};
	r.expect(T!(";"))?;
	Ok(InterfaceMember::CallSignature(CallSignature {
		type_params,
		parameters,
		return_type,
	}))
}
// 解析构造签名: new (...): type
fn parse_construct_signature<'lex>(r: &mut Lexer<'lex>) -> Result<InterfaceMember<'lex>, Error<'lex>> {
	// r.expect(T!("new"))?;

	// 解析泛型参数
	let type_params = TypeParam::parse_list(r)?;
	// 解析参数列表
	let parameters = FuncParam::parse_list(r)?;
	// 解析返回类型
	let return_type = if r.if_is_next(T!(":")) {
		TypeExpr::parse(r)?
	} else {
		TypeExpr::Unsupport
	};
	r.expect(T!(";"))?;
	Ok(InterfaceMember::ConstructSignature(ConstructSignature {
		type_params,
		parameters,
		return_type,
	}))
}

/// Class declaration
/// class ident<type_param...> extends type_expr implements type_expr... {
/// 	class_member...
/// }
#[derive(Debug, Clone)]
pub struct Class<'src> {
	pub name: &'src str,
	pub type_params: Vec<TypeParam<'src>>,
	pub extends: Option<TypeExpr<'src>>,
	pub implements: Vec<TypeExpr<'src>>,
	pub members: Vec<ClassMember<'src>>,
}
impl<'src, 'lex> Parse<'lex> for Class<'src> {
	type Output = Class<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// r.expect_ident_eq("class")?;
		let name = r.expect_ident()?;
		let type_params = TypeParam::parse_list(r)?;

		let extends = if r.if_is_ident_next("extends") {
			Some(TypeExpr::parse(r)?)
		} else {
			None
		};

		let implements = if r.if_is_ident_next("implements") {
			TypeExpr::parse_list(r)?
		} else {
			Vec::new()
		};

		r.expect(T!("{"))?;
		let mut members = Vec::new();
		while !r.is(T!("}")) {
			members.push(ClassMember::parse(r)?);
		}
		r.expect(T!("}"))?;

		Ok(Class {
			name,
			type_params,
			extends,
			implements,
			members,
		})
	}
}

/// Class member
#[derive(Debug, Clone)]
pub enum ClassMember<'src> {
	Property(Property<'src>),
	Method(Method<'src>),
	Constructor(Constructor<'src>),
	Getter(Getter<'src>),
	Setter(Setter<'src>),
	IndexSignature(IndexSignature<'src>),
}
impl<'src, 'lex> Parse<'lex> for ClassMember<'src> {
	type Output = ClassMember<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		// 解析访问修饰符和修饰符
		let mut access_modifier = None; // public, private, protected
		let mut is_static = false;
		let mut is_readonly = false;
		let mut _is_abstract = false;

		// 循环解析所有修饰符
		loop {
			match r.peek()?.token {
				Token::Ident("public") | Token::Ident("private") | Token::Ident("protected") => {
					let modifier = r.next()?;
					access_modifier = Some(modifier.token);
				}
				Token::Ident("static") => {
					r.next()?;
					is_static = true;
				}
				Token::Ident("readonly") => {
					r.next()?;
					is_readonly = true;
				}
				Token::Ident("abstract") => {
					r.next()?;
					if r.is(T!("?")) {
						r.next()?;
						r.next()?;
						// TODO abstract?: string;
						let type_expr = TypeExpr::parse(r)?;
						r.expect(T!(";"))?;
						return Ok(ClassMember::Property(Property {
							name: "abstract",
							is_optional: true,
							is_readonly,
							type_expr,
						}));
					}
					_is_abstract = true;
				}
				Token::Ident("get") | Token::Ident("set") | Token::Ident("constructor") => {
					// 这些是特殊成员的关键字，跳出循环
					break;
				}
				T!("[") => {
					// 索引签名，跳出循环
					break;
				}
				v => {
					// 尝试解析标识符作为成员名
					if let Some(_ident) = r.peek_ident() {
						// TODO
						break;
					} else {
						return Err(Error::Unsupport(r.span(), v, "class member"));
					}
				}
			}
		}

		// 检查是否是索引签名
		if r.is(T!("[")) {
			return parse_class_index_signature(r, is_readonly);
		}

		// 检查是否是 getter
		if r.if_is_ident_next("get") {
			if r.is(T!("(")) || r.is(T!("<")) {
				// 解析泛型参数
				let type_params = TypeParam::parse_list(r)?;

				// 解析参数列表
				let parameters = FuncParam::parse_list(r)?;

				// 解析返回类型
				let return_type = if r.if_is_next(T!(":")) {
					TypeExpr::parse(r)?
				} else {
					// 默认返回类型为 void
					TypeExpr::Unsupport
				};

				r.expect(T!(";"))?;
				return Ok(ClassMember::Method(Method {
					name: "get",
					is_optional: false,
					type_params,
					parameters,
					return_type,
				}));
			} else {
				return parse_getter(r, access_modifier, is_static);
			}
		}

		// 检查是否是 setter
		if r.if_is_ident_next("set") {
			if r.is(T!("(")) || r.is(T!("<")) {
				// 解析泛型参数
				let type_params = TypeParam::parse_list(r)?;

				// 解析参数列表
				let parameters = FuncParam::parse_list(r)?;

				// 解析返回类型
				let return_type = if r.if_is_next(T!(":")) {
					TypeExpr::parse(r)?
				} else {
					// 默认返回类型为 void
					TypeExpr::Unsupport
				};

				r.expect(T!(";"))?;
				return Ok(ClassMember::Method(Method {
					name: "set",
					is_optional: false,
					type_params,
					parameters,
					return_type,
				}));
			} else {
				return parse_setter(r, access_modifier, is_static);
			}
		}

		// 检查是否是构造函数
		if r.if_is_ident_next("constructor") {
			return parse_constructor(r, access_modifier, is_static);
		}

		// 解析成员名称
		let name = r.expect_ident()?;

		// 检查是否是可选成员
		let is_optional = r.if_is_next(T!("?"));

		// 根据接下来的符号判断是属性还是方法
		r.push();
		match r.peek()?.token {
			T!("=") => {
				r.next()?;
				//         readonly ignoreBOM = false;
				let type_expr = TypeExpr::parse(r)?;
				r.expect(T!(";"))?;
				r.pop(false);
				Ok(ClassMember::Property(Property {
					name,
					is_optional,
					is_readonly,
					type_expr,
				}))
			}
			// 属性: name: type;
			T!(":") => {
				r.next()?;
				let type_expr = TypeExpr::parse(r)?;
				r.expect(T!(";"))?;
				r.pop(false);
				Ok(ClassMember::Property(Property {
					name,
					is_optional,
					is_readonly,
					type_expr,
				}))
			}
			// 方法: name<?>(...): type;
			T!("<") | T!("(") => {
				// 解析泛型参数
				let type_params = TypeParam::parse_list(r)?;

				// 解析参数列表
				let parameters = FuncParam::parse_list(r)?;

				// 解析返回类型
				let return_type = if r.if_is_next(T!(":")) {
					TypeExpr::parse(r)?
				} else {
					// 默认返回类型为 void
					TypeExpr::Unsupport
				};

				r.expect(T!(";"))?;
				r.pop(false);
				Ok(ClassMember::Method(Method {
					name,
					is_optional,
					type_params,
					parameters,
					return_type,
				}))
			}
			_ => {
				// 回退到属性解析
				r.pop(true);
				let name = r.expect_ident()?;
				let is_optional = r.if_is_next(T!("?"));
				r.expect(T!(":"))?;
				let type_expr = TypeExpr::parse(r)?;
				r.expect(T!(";"))?;

				Ok(ClassMember::Property(Property {
					name,
					is_optional,
					is_readonly: false,
					type_expr,
				}))
			}
		}
		// let _is_static = r.if_is_ident_next("static");
		// let is_readonly = r.if_is_ident_next("readonly");
		// let name = r.expect_ident()?;
		// if r.is(T!(":")) {
		// 	// Property
		// 	r.next()?;
		// 	let type_expr = TypeExpr::parse(r)?;
		// 	r.expect(T!(";"))?;

		// 	Ok(ClassMember::Property(Property {
		// 		name,
		// 		is_optional: false,
		// 		is_readonly,
		// 		type_expr,
		// 	}))
		// } else if r.is(T!("(")) {
		// 	// Method
		// 	let parameters = FuncParam::parse_list(r)?;
		// 	r.expect(T!(":"))?;
		// 	let return_type = TypeExpr::parse(r)?;
		// 	r.expect(T!(";"))?;

		// 	Ok(ClassMember::Method(Method {
		// 		name,
		// 		is_optional: false,
		// 		type_params: Vec::new(),
		// 		parameters,
		// 		return_type,
		// 	}))
		// } else if name == "constructor" {
		// 	// Constructor
		// 	let parameters = FuncParam::parse_list(r)?;
		// 	r.expect(T!(";"))?;

		// 	Ok(ClassMember::Constructor(Constructor { parameters }))
		// } else {
		// 	Err(Error::UnexpectChar(r.span()))
		// }
	}
}

// 解析类中的索引签名
fn parse_class_index_signature<'lex>(r: &mut Lexer<'lex>, is_readonly: bool) -> Result<ClassMember<'lex>, Error<'lex>> {
	r.expect(T!("["))?;
	r.push();
	fn parse_with_name<'lex>(r: &mut Lexer<'lex>, is_readonly: bool) -> Result<ClassMember<'lex>, Error<'lex>> {
		// 解析索引参数
		let param_name = r.expect_ident()?;
		r.expect(T!(":"))?;

		// 索引键类型通常是 string | number | symbol
		let key_type = TypeExpr::parse(r)?;
		r.expect(T!("]"))?;

		// TODO
		r.if_is_next(T!("("));
		r.if_is_next(T!(")"));

		// 解析返回类型
		r.expect(T!(":"))?;
		let return_type = TypeExpr::parse(r)?;
		r.expect(T!(";"))?;

		Ok(ClassMember::IndexSignature(IndexSignature {
			parameter: FuncParam {
				name: param_name,
				type_expr: key_type,
				is_optional: false,
				dotdotdot: false,
			},
			is_readonly,
			return_type,
		}))
	}
	match parse_with_name(r, is_readonly) {
		Ok(v) => {
			r.pop(false);
			Ok(v)
		}
		Err(_) => {
			r.pop(true);
			// 索引键类型通常是 string | number | symbol
			let key_type = TypeExpr::parse(r)?;
			r.expect(T!("]"))?;

			// TODO    [Symbol.iterator](): IterableIterator<T>;
			r.if_is_next(T!("("));
			r.if_is_next(T!(")"));

			// 解析返回类型
			r.expect(T!(":"))?;
			let return_type = TypeExpr::parse(r)?;
			r.expect(T!(";"))?;

			Ok(ClassMember::IndexSignature(IndexSignature {
				parameter: FuncParam {
					name: "",
					type_expr: key_type,
					is_optional: false,
					dotdotdot: false,
				},
				is_readonly,
				return_type,
			}))
		}
	}

	// r.expect(T!("["))?;

	// // 解析索引参数
	// let param_name = r.expect_ident()?;
	// r.expect(T!(":"))?;

	// // 索引键类型通常是 string | number
	// let key_type = TypeExpr::parse(r)?;
	// r.expect(T!("]"))?;

	// // 解析返回类型
	// r.expect(T!(":"))?;
	// let return_type = TypeExpr::parse(r)?;
	// r.expect(T!(";"))?;

	// Ok(ClassMember::IndexSignature(IndexSignature {
	// 	is_readonly,
	// 	parameter: FuncParam {
	// 		name: param_name,
	// 		dotdotdot: false,
	// 		is_optional: false,
	// 		type_expr: key_type,
	// 	},
	// 	return_type,
	// }))
}

// 解析 getter
fn parse_getter<'lex>(r: &mut Lexer<'lex>, _access_modifier: Option<Token>, _is_static: bool) -> Result<ClassMember<'lex>, Error<'lex>> {
	// 解析属性名
	let name = r.expect_ident()?;

	// 解析参数列表（getter 应该没有参数或只有空参数列表）
	r.expect(T!("("))?;
	r.expect(T!(")"))?;

	// 解析返回类型
	r.expect(T!(":"))?;
	let return_type = TypeExpr::parse(r)?;
	r.expect(T!(";"))?;

	Ok(ClassMember::Getter(Getter { name, return_type }))
}

// 解析 setter
fn parse_setter<'lex>(r: &mut Lexer<'lex>, _access_modifier: Option<Token>, _is_static: bool) -> Result<ClassMember<'lex>, Error<'lex>> {
	// 解析属性名
	let name = r.expect_ident()?;

	// 解析参数列表（setter 应该只有一个参数）
	r.expect(T!("("))?;
	let parameter = FuncParam::parse(r)?;
	r.expect(T!(")"))?;

	// setter 通常没有返回类型或返回 void
	if r.if_is_next(T!(":")) {
		TypeExpr::parse(r)?; // 解析但忽略返回类型
	}

	r.expect(T!(";"))?;

	Ok(ClassMember::Setter(Setter { name, parameter }))
}

// 解析构造函数
fn parse_constructor<'lex>(
	r: &mut Lexer<'lex>,
	_access_modifier: Option<Token>,
	_is_static: bool,
) -> Result<ClassMember<'lex>, Error<'lex>> {
	// 解析参数列表
	let parameters = FuncParam::parse_list(r)?;

	// 构造函数可能有返回类型注解，但通常省略
	if r.if_is_next(T!(":")) {
		TypeExpr::parse(r)?; // 解析但忽略返回类型
	}

	r.expect(T!(";"))?;

	Ok(ClassMember::Constructor(Constructor { parameters }))
}

/// Property declaration
#[derive(Debug, Clone)]
pub struct Property<'src> {
	pub name: &'src str,
	pub is_optional: bool,
	pub is_readonly: bool,
	pub type_expr: TypeExpr<'src>,
}

/// Method declaration
#[derive(Debug, Clone)]
pub struct Method<'src> {
	pub name: &'src str,
	pub is_optional: bool,
	pub type_params: Vec<TypeParam<'src>>,
	pub parameters: Vec<FuncParam<'src>>,
	pub return_type: TypeExpr<'src>,
}

/// Index signature
#[derive(Debug, Clone)]
pub struct IndexSignature<'src> {
	pub is_readonly: bool,
	pub parameter: FuncParam<'src>,
	pub return_type: TypeExpr<'src>,
}

/// Call signature
#[derive(Debug, Clone)]
pub struct CallSignature<'src> {
	pub type_params: Vec<TypeParam<'src>>,
	pub parameters: Vec<FuncParam<'src>>,
	pub return_type: TypeExpr<'src>,
}

/// Construct signature
#[derive(Debug, Clone)]
pub struct ConstructSignature<'src> {
	pub type_params: Vec<TypeParam<'src>>,
	pub parameters: Vec<FuncParam<'src>>,
	pub return_type: TypeExpr<'src>,
}

/// Constructor declaration
#[derive(Debug, Clone)]
pub struct Constructor<'src> {
	pub parameters: Vec<FuncParam<'src>>,
}

/// Getter declaration
#[derive(Debug, Clone)]
pub struct Getter<'src> {
	pub name: &'src str,
	pub return_type: TypeExpr<'src>,
}

/// Setter declaration
#[derive(Debug, Clone)]
pub struct Setter<'src> {
	pub name: &'src str,
	pub parameter: FuncParam<'src>,
}

/// Parameter declaration
/// ident?:type_expr
#[derive(Debug, Clone)]
pub struct FuncParam<'src> {
	pub name: &'src str,
	pub dotdotdot: bool,
	pub is_optional: bool,
	pub type_expr: TypeExpr<'src>,
}
impl<'src, 'lex> Parse<'lex> for FuncParam<'src> {
	type Output = FuncParam<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		let dotdotdot = r.if_is_next(T!("..."));
		let name = r.expect_ident()?;
		let is_optional = r.if_is_next(T!("?"));
		r.expect(T!(":"))?;
		let type_expr = TypeExpr::parse(r)?;
		Ok(FuncParam {
			name,
			dotdotdot,
			is_optional,
			type_expr,
		})
	}
}
impl<'src> FuncParam<'src> {
	// (ident:type_expr,ident:type_expr)
	fn parse_list<'lex>(r: &mut Lexer<'lex>) -> Result<Vec<FuncParam<'lex>>, Error<'lex>> {
		r.expect(T!("("))?;
		let mut parameters = Vec::new();
		while !r.is(T!(")")) {
			parameters.push(FuncParam::parse(r)?);
			r.if_is_next(T!(","));
		}
		r.expect(T!(")"))?;
		Ok(parameters)
	}
}

/// Type parameter
/// ident extends type_expr = type_expr
#[derive(Debug, Clone)]
pub struct TypeParam<'src> {
	pub name: &'src str,
	pub constraint: Option<TypeExpr<'src>>,
	pub default: Option<TypeExpr<'src>>,
}
impl<'src, 'lex> Parse<'lex> for TypeParam<'src> {
	type Output = TypeParam<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		let name = r.expect_ident()?;
		let constraint = if r.if_is_ident_next("extends") {
			Some(TypeExpr::parse(r)?)
		} else {
			None
		};
		let default = if r.if_is_next(T!("=")) {
			Some(TypeExpr::parse(r)?) //
		} else {
			None
		};
		Ok(TypeParam { name, constraint, default })
	}
}
impl<'src> TypeParam<'src> {
	// <type_param,type_param>
	fn parse_list<'lex>(r: &mut Lexer<'lex>) -> Result<Vec<TypeParam<'lex>>, Error<'lex>> {
		if !r.if_is_next(T!("<")) {
			return Ok(Vec::new());
		}
		let mut params = Vec::new();
		while !r.is(T!(">")) {
			params.push(TypeParam::parse(r)?);
			r.if_is_next(T!(","));
		}
		r.expect(T!(">"))?;
		Ok(params)
	}
}

/// Type expression
#[derive(Debug, Clone)]
pub enum TypeExpr<'src> {
	Array(Box<TypeExpr<'src>>),
	Tuple(Vec<TypeExpr<'src>>),
	Union(Vec<TypeExpr<'src>>),
	Intersection(Vec<TypeExpr<'src>>),
	Function(FunctionType<'src>),
	Constructor(ConstructorType<'src>),
	Literal(LiteralType<'src>),
	TypeRef(TypeRef<'src>),
	IndexedAccess(IndexedAccessType<'src>),
	Mapped(MappedType<'src>),
	Conditional(ConditionalType<'src>),
	Infer(Box<InferType<'src>>),
	KeyOf(Box<TypeExpr<'src>>),
	TypeOf(Box<TypeExpr<'src>>),
	Import {
		path: &'src str,
		modules: Vec<&'src str>,
		type_param: Vec<TypeParam<'src>>,
	},
	Unsupport,
}
impl<'src, 'lex> Parse<'lex> for TypeExpr<'src> {
	type Output = TypeExpr<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		TypeExpr::parse_union(r)
	}
}
impl<'src> TypeExpr<'src> {
	// <type_expr,type_expr>
	fn parse_args<'lex>(r: &mut Lexer<'lex>) -> Result<Vec<TypeExpr<'lex>>, Error<'lex>> {
		if !r.if_is_next(T!("<")) {
			return Ok(Vec::new());
		}
		let mut args = Vec::new();
		while !r.is(T!(">")) {
			args.push(TypeExpr::parse(r)?);
			r.if_is_next(T!(","));
		}
		r.expect(T!(">"))?;
		Ok(args)
	}
	// type_expr,type_expr
	fn parse_list<'lex>(r: &mut Lexer<'lex>) -> Result<Vec<TypeExpr<'lex>>, Error<'lex>> {
		let mut types = Vec::new();
		loop {
			types.push(TypeExpr::parse(r)?);
			if !r.if_is_next(T!(",")) {
				break;
			}
		}
		Ok(types)
	}
	// 解析联合类型：string | number | boolean
	fn parse_union<'lex>(r: &mut Lexer<'lex>) -> Result<TypeExpr<'lex>, Error<'lex>> {
		let mut types = vec![TypeExpr::parse_intersection(r)?];
		while r.if_is_next(T!("|")) {
			types.push(TypeExpr::parse_intersection(r)?);
		}
		if types.len() == 1 {
			Ok(types.remove(0))
		} else {
			Ok(TypeExpr::Union(types))
		}
	}
	// 解析交叉类型：A & B & C
	fn parse_intersection<'lex>(r: &mut Lexer<'lex>) -> Result<TypeExpr<'lex>, Error<'lex>> {
		let mut types = vec![TypeExpr::parse_function_or_constructor(r)?];
		while r.if_is_next(T!("&")) {
			types.push(TypeExpr::parse_function_or_constructor(r)?);
		}
		if types.len() == 1 {
			Ok(types.remove(0))
		} else {
			Ok(TypeExpr::Intersection(types))
		}
	}
	// 解析函数类型或构造器类型
	fn parse_function_or_constructor<'lex>(r: &mut Lexer<'lex>) -> Result<TypeExpr<'lex>, Error<'lex>> {
		match r.peek()?.token {
			// 检查是否是构造器类型：new (x: number) => MyClass
			Token::Ident("new") => {
				r.next()?;
				let parameters = FuncParam::parse_list(r)?;
				r.expect(T!("=>"))?;
				let return_type = TypeExpr::parse_union(r)?; // 返回类型可以是联合类型
				Ok(TypeExpr::Constructor(ConstructorType {
					type_params: Vec::new(),
					parameters,
					return_type: Box::new(return_type),
				}))
			}
			// 检查是否是函数类型：(x: number, y: string) => boolean
			T!("(") => {
				r.push();
				let Ok(parameters) = FuncParam::parse_list(r) else {
					r.pop(true);
					return TypeExpr::parse_type_with_suffix(r);
				};
				// 如果后面是 =>，说明是函数类型
				if r.if_is_next(T!("=>")) {
					let return_type = TypeExpr::parse_union(r)?;
					r.pop(false);
					Ok(TypeExpr::Function(FunctionType {
						type_params: Vec::new(),
						parameters,
						return_type: Box::new(return_type),
					}))
				} else {
					// 如果不是函数类型，回退到括号表达式
					r.pop(true);
					TypeExpr::parse_type_with_suffix(r)
				}
			}
			T!("<") => {
				// export declare type TypeDecorator = <T>(type: TypeConstructor<T>) => PropertyDecorator;
				let type_params = TypeParam::parse_list(r)?;
				let parameters = FuncParam::parse_list(r)?;
				r.expect(T!("=>"))?;
				let return_type = TypeExpr::parse_union(r)?;
				Ok(TypeExpr::Function(FunctionType {
					type_params,
					parameters,
					return_type: Box::new(return_type),
				}))
			}
			_ => TypeExpr::parse_type_with_suffix(r),
		}
	}
	fn parse_type_with_suffix<'lex>(r: &mut Lexer<'lex>) -> Result<TypeExpr<'lex>, Error<'lex>> {
		let mut expr = TypeExpr::parse_prefix_type(r)?;
		// 处理类型后缀
		loop {
			expr = TypeExpr::parse_type_suffix(r, expr)?;
			if !matches!(r.peek()?.token, T!("[")) {
				break;
			}
		}
		Ok(expr)
	}
	// 处理类型后缀
	fn parse_type_suffix<'lex>(r: &mut Lexer<'lex>, base: TypeExpr<'lex>) -> Result<TypeExpr<'lex>, Error<'lex>> {
		match r.peek()?.token {
			// 数组后缀：Type[]
			T!("[") => {
				r.next()?;
				if r.if_is_next(T!("]")) {
					Ok(TypeExpr::Array(Box::new(base)))
				} else {
					// 索引访问类型：Type[Key]
					let index_type = TypeExpr::parse_union(r)?;
					r.expect(T!("]"))?;
					Ok(TypeExpr::IndexedAccess(IndexedAccessType {
						object_type: Box::new(base),
						index_type: Box::new(index_type),
					}))
				}
			}
			_ => Ok(base),
		}
	}
	// 解析主要类型（最高优先级）
	fn parse_prefix_type<'lex>(r: &mut Lexer<'lex>) -> Result<TypeExpr<'lex>, Error<'lex>> {
		match r.peek()?.token {
			Token::Ident("keyof") => {
				r.next()?;
				// export type ElementAttributeKeys = keyof ElementAttributeValues;
				Ok(TypeExpr::KeyOf(Box::new(TypeExpr::parse(r)?)))
			}
			Token::Ident("typeof") => {
				r.next()?;
				// readonly self: WorkerGlobalScope & typeof globalThis;
				Ok(TypeExpr::TypeOf(Box::new(TypeExpr::parse(r)?)))
			}
			Token::Ident("import") => {
				r.next()?;
				r.expect(T!("("))?;
				let path = r.expect_string()?;
				r.expect(T!(")"))?;
				let mut modules: Vec<&'lex str> = Vec::new();
				while r.if_is_next(T!(".")) {
					modules.push(r.expect_ident()?);
				}
				let type_param = TypeParam::parse_list(r)?;
				Ok(TypeExpr::Import { path, modules, type_param })
			}
			Token::Ident(ident) => {
				r.next()?;
				let mut name = ident;
				let mut modules: Vec<&'lex str> = Vec::new();
				// 解析模块路径：module.submodule.TypeName
				while r.if_is_next(T!(".")) {
					modules.push(name);
					name = r.expect_ident()?;
				}
				// 解析类型参数：Array<string>
				let type_args = TypeExpr::parse_args(r)?;
				Ok(TypeExpr::TypeRef(TypeRef { name, modules, type_args }))
			}
			Token::Number(v) => {
				r.next()?;
				Ok(TypeExpr::Literal(LiteralType::Number(v)))
			}
			Token::String(v) => {
				r.next()?;
				Ok(TypeExpr::Literal(LiteralType::String(v)))
			}
			Token::Template(v) => {
				r.next()?;
				Ok(TypeExpr::Literal(LiteralType::Template(v)))
			}
			T!("(") => {
				r.next()?;
				let expr = TypeExpr::parse_union(r)?; // 解析括号内的表达式

				// 检查是否是带括号的函数类型
				if r.if_is_next(T!("=>")) {
					// 这种情况： (T) => R，实际上是一个函数类型
					let return_type = TypeExpr::parse_union(r)?;
					r.expect(T!(")"))?;

					// 将括号内的表达式作为单个参数
					let parameters = vec![FuncParam {
						name: "", // 匿名参数
						type_expr: expr,
						is_optional: false,
						dotdotdot: false,
					}];

					Ok(TypeExpr::Function(FunctionType {
						type_params: Vec::new(),
						parameters,
						return_type: Box::new(return_type),
					}))
				} else {
					r.expect(T!(")"))?;
					Ok(expr) // 返回括号内的表达式
				}
			}
			T!("[") => {
				// type Matrix4Result = [number, number]
				r.next()?;
				let mut elements = Vec::new();
				while !r.is(T!("]")) {
					elements.push(TypeExpr::parse_union(r)?);
					if r.if_is_next(T!("?")) {
						// TODO
					}
					if r.if_is_next(T!(":")) {
						// declare type AnimationRange<T> = [from: T,to: T];
						TypeExpr::parse_union(r)?;
						// TODO
					}
					if !r.is(T!("]")) {
						r.expect(T!(","))?;
					}
				}
				r.expect(T!("]"))?;
				if elements.len() == 1 {
					Ok(TypeExpr::Array(Box::new(elements.remove(0))))
				} else {
					Ok(TypeExpr::Tuple(elements))
				}
			}
			T!("{") => {
				// 简单对象类型或映射类型 { [key: string]: value }
				// 这里简化为不支持，实际需要更复杂的解析
				r.next()?;
				// TODO
				r.next_until(T!("}"))?;
				r.expect(T!("}"))?;
				Ok(TypeExpr::Unsupport) // 简化处理
			}
			T!("<") => {
				// 条件类型：T extends U ? X : Y
				r.next()?;
				let check_type = TypeExpr::parse_union(r)?;
				r.expect(Token::Ident("extends"))?;
				let extends_type = TypeExpr::parse_union(r)?;
				r.expect(T!("?"))?;
				let true_type = TypeExpr::parse_union(r)?;
				r.expect(T!(":"))?;
				let false_type = TypeExpr::parse_union(r)?;
				r.expect(T!(">"))?;

				Ok(TypeExpr::Conditional(ConditionalType {
					check_type: Box::new(check_type),
					extends_type: Box::new(extends_type),
					true_type: Box::new(true_type),
					false_type: Box::new(false_type),
				}))
			}
			// TODO
			// Token::Ident("infer") => {
			// 	r.next()?;
			// 	let name = r.expect_ident()?;
			// 	Ok(TypeExpr::Infer(Box::new(InferType { name })))
			// }
			v => Err(Error::Unsupport(r.span(), v, "TypeExpr")),
		}
	}
}

/// Function type
#[derive(Debug, Clone)]
pub struct FunctionType<'src> {
	pub type_params: Vec<TypeParam<'src>>,
	pub parameters: Vec<FuncParam<'src>>,
	pub return_type: Box<TypeExpr<'src>>,
}

/// Constructor type
#[derive(Debug, Clone)]
pub struct ConstructorType<'src> {
	pub type_params: Vec<TypeParam<'src>>,
	pub parameters: Vec<FuncParam<'src>>,
	pub return_type: Box<TypeExpr<'src>>,
}

/// Literal type
#[derive(Debug, Clone)]
pub enum LiteralType<'src> {
	String(&'src str),
	Number(&'src str),
	Template(&'src str),
	Boolean(bool),
}

/// Type reference
#[derive(Debug, Clone)]
pub struct TypeRef<'src> {
	pub name: &'src str,
	pub modules: Vec<&'src str>,
	pub type_args: Vec<TypeExpr<'src>>,
}

/// Indexed access type
#[derive(Debug, Clone)]
pub struct IndexedAccessType<'src> {
	pub object_type: Box<TypeExpr<'src>>,
	pub index_type: Box<TypeExpr<'src>>,
}

/// Mapped type
#[derive(Debug, Clone)]
pub struct MappedType<'src> {
	pub key: &'src str,
	pub constraint: Box<TypeExpr<'src>>,
	pub value_type: Box<TypeExpr<'src>>,
}

/// Conditional type
#[derive(Debug, Clone)]
pub struct ConditionalType<'src> {
	pub check_type: Box<TypeExpr<'src>>,
	pub extends_type: Box<TypeExpr<'src>>,
	pub true_type: Box<TypeExpr<'src>>,
	pub false_type: Box<TypeExpr<'src>>,
}

/// Infer type
#[derive(Debug, Clone)]
pub struct InferType<'src> {
	pub type_param: TypeParam<'src>,
}

/// Expression (for const values)
#[derive(Debug, Clone)]
pub struct Expr<'src> {
	pub items: Vec<ExprItem<'src>>,
}
impl<'src, 'lex> Parse<'lex> for Expr<'src> {
	type Output = Expr<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		let mut items = Vec::new();
		while let Ok(item) = ExprItem::parse(r) {
			r.next()?;
			items.push(item);
		}
		Ok(Expr { items })
	}
}
#[derive(Debug, Clone)]
pub enum ExprItem<'src> {
	String(&'src str),
	Number(&'src str),
	Boolean(bool),
	Null,
	Ident(&'src str),
	Minus,
	Plus,
	Shl,
	Shr,
	Dot,
	Or,
}
impl<'src, 'lex> Parse<'lex> for ExprItem<'src> {
	type Output = ExprItem<'lex>;
	fn parse(r: &mut Lexer<'lex>) -> Result<Self::Output, Error<'lex>> {
		match r.peek()?.token {
			Token::Minus => Ok(ExprItem::Minus),
			Token::Plus => Ok(ExprItem::Plus),
			Token::Less => {
				r.next()?;
				match r.peek()?.token {
					Token::Less => {}
					v => return Err(Error::Unsupport(r.span(), v, "expr unsurport")),
				}
				Ok(ExprItem::Shl)
			}
			Token::Dot => Ok(ExprItem::Dot),
			Token::Greater => {
				r.next()?;
				match r.peek()?.token {
					Token::Greater => {}
					v => return Err(Error::Unsupport(r.span(), v, "expr unsurport")),
				}
				Ok(ExprItem::Shr)
			}
			Token::Or => Ok(ExprItem::Or),
			Token::Number(v) => Ok(ExprItem::Number(v)),
			Token::String(v) => Ok(ExprItem::String(v)),
			Token::Ident(v) => match v {
				"true" => Ok(ExprItem::Boolean(true)),
				"false" => Ok(ExprItem::Boolean(false)),
				"null" => Ok(ExprItem::Null),
				v => Ok(ExprItem::Ident(v)),
			},
			v => Err(Error::Unsupport(r.span(), v, "expr unsurport")),
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_import() {
		let src = r#"
// 导入单个具名导出
import { Button } from './components';

// 导入多个具名导出
import { Button, Input, Card } from './components';

// 导入并重命名
import { Button as Btn } from './components';

// 混合重命名
import { Button as Btn, Input as TextInput } from './components';

// 导入默认导出
import React from 'react';
import MyComponent from './MyComponent';

// 导入所有导出到单个命名空间
import * as Components from './components';
import * as Lodash from 'lodash';

// 默认导入 + 命名导入
import React, { useState, useEffect } from 'react';

// 默认导入 + 命名空间导入
import defaultExport, * as namedExports from './module';

// 默认导入 + 具名导入 + 重命名
import JQuery, { ajax as httpRequest } from 'jquery';

// 仅导入类型
import type { User, Product } from './types';
import { type User, type Product } from './types';

// 导入类型和值
import { type User, getUser } from './api';

// 命名空间类型导入
import type * as Types from './types';
		"#;
		let mut r = Lexer::new(src);
		let res = DeclFile::parse(&mut r).unwrap();
		println!("{:#?}", res);
	}
}

#[test]
fn test_namespace() {
	let src = r#"
declare namespace wifiext {
    function getSupportedPowerModel(): Promise<Array<PowerModel>>;
	export interface AutoSaveCallback {
		onSuccess(): void;
	}
}
export default wifiext;
"#;
	println!("{:#?}", DeclFile::parse(&mut Lexer::new(src)).unwrap());
}
#[test]
fn test_export() {
	let src = r#"
export { ToneMappingType, ToneMappingSettings, PostProcessSettings, BloomSettings } from './graphics3d/ScenePostProcessSettings';
export import NetAddress = connection.NetAddress;
export type KioskStatus = _KioskStatus;
export type { Progress };
export default wifiext;
"#;
	println!("{:#?}", DeclFile::parse(&mut Lexer::new(src)).unwrap());
}

#[test]
fn test_interface() {
	let src = r#"
export interface TCPExtraOptions extends ExtraOptionsBase {
	keepAlive?: boolean;
	OOBInline?: boolean;
	TCPNoDelay?: boolean;
	socketLinger?: {
		on: boolean;
		linger: number;
	};
}
"#;
	println!("{:#?}", DeclFile::parse(&mut Lexer::new(src)).unwrap());
}

#[test]
fn test_enum() {
	let src = r#"
    enum PathIteratorVerb {
        MOVE = 0,
        LINE = 1,
        QUAD = 2,
        CONIC = 3,
        CUBIC = 4,
        CLOSE = 5,
        DONE = CLOSE + 1,
        UNDERLINE_THICKNESS_VALID = 1 << 0,
		UNDERLINE_POSITION_VALID = 1 << 1,
    }
"#;
	println!("{:#?}", DeclFile::parse(&mut Lexer::new(src)).unwrap());
}

#[test]
fn test_class() {
	let src = r#"
// declare class ReadStream extends stream.Readable {
// }
// export declare abstract class FrameCallback {
// }
class GenericsTask<A extends Array<Object>, R> extends Task {
}
"#;
	println!("{:#?}", DeclFile::parse(&mut Lexer::new(src)).unwrap());
}
#[test]
fn test_const() {
	let src = r#"
const enum DragStatus {
}
"#;
	println!("{:#?}", DeclFile::parse(&mut Lexer::new(src)).unwrap());
}
#[test]
fn test_type_expr() {
	let src = r#"
// function stringify(value: Object, replacer?: (number | string)[] | null, space?: string | number): string;
interface ParticleConfigs {
    [ParticleType.POINT]: PointParticleParameters;
}
"#;
	println!("{:#?}", DeclFile::parse(&mut Lexer::new(src)).unwrap());
}
